package com.gym.core.xml;

import java.io.ByteArrayInputStream;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * 
 * @author 532002108@qq.com
 * @date 2015-9-9 上午11:09:10
 */
public class XmlUtils {

    private static final Logger logger = LoggerFactory.getLogger(XmlUtils.class);

    public static <T> String produceXml(T t) {
        Class<?> classType = t.getClass();
        StringWriter writer = new StringWriter();
        try {
            Marshaller marshaller = JAXBContext.newInstance(classType).createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.setProperty(Marshaller.JAXB_FRAGMENT, false);
            marshaller.marshal(t, writer);
        } catch (JAXBException e) {
            logger.error(e.getMessage(), e);
        }
        return writer.toString();
    }

    
    @SuppressWarnings("unchecked")
	public static <T> T parseXml(String xml, Class<T> classType) {
        try {
            Unmarshaller jaxbUnmarshaller = JAXBContext.newInstance(classType).createUnmarshaller();
            return (T) jaxbUnmarshaller.unmarshal(new ByteArrayInputStream(xml.getBytes()));
        } catch (JAXBException e) {
            logger.error(e.getMessage(), e);
        }
        return null;
    }

}
